﻿function isNumber(event) {
  if (event) {
    var charCode = (event.which) ? event.which : event.keyCode;
    if (charCode != 190 && charCode > 31 && 
       (charCode < 48 || charCode > 57) && 
       (charCode < 96 || charCode > 105) && 
       (charCode < 37 || charCode > 40) && 
        charCode != 110 && charCode != 8 && charCode != 46 )
       return false;
  }
  return true;
}

$(document).ready(function() {

$("#users_div").hide();
$("#info_div").hide();
$("#add_user_dialog").hide();
$("#rfid_dialog").hide();
$("#rfid_save_dialog").hide();

$( ".choose_user" ).change(function() {
	$( "select option:selected" ).each(function() {
		$.ajax({
		type: "POST",
		url: "change_session_uid.php",
		data: { data: $( this ).text() }
	})
	.done(function( msg ) {
		window.location.href = '?';
	});
	});
});

var SearchString = window.location.search.substring(1);
var VariableArray = SearchString.split('?=');
if(VariableArray[0] == "new_user") {
	$("#info_div").hide();
	$("#ground").css("height", "auto");
	$("#users_div").show();
	$("#calendar").hide();
	$("#bottom").hide();
	$("#external-events").hide();
}

var work_status = 0; // wyswietlania statusu pracuje/nie pracuje

var event_id = 1; //liczenie eventow dla urlopow

var vacations_events = new Array(); // do zapisu eventow do bazy danych

var vacations = 1; // zakladka urlop otwarta/z
var vacations_title = 0;

$( "#external-events" ).hide();

$( "#rfid_reader" ).click(function() {

 $( "#progressbar" ).progressbar({
value: false
});

 $( "#rfid_dialog" ).dialog({
	position: { my: "center top", at: "center bottom", of: ground },
	resizable: false,
	dialogClass: "no-close"
});

		$.ajax({
		type: "POST",
		url: "read_rfid.php",
		//data: dataString,
		dataType: 'json',
		success: function (data) {
			$( "#name" ).text(data.name);
			$( "#name" ).val(data.name);
			$( "#locker" ).text(data.locker);
			$( "#locker" ).val(data.locker);
			$( "#machine" ).text(data.machine);
			$( "#machine" ).val(data.machine);
			$("#rfid_dialog").dialog("close");
		}
		//timeout: 5000,]
		//beforeSend: function() {
		//	$("#rfid_reader").text("odczytywanie..");
        //}
//})
	//.done(function( msg ) {
	//	$("#rfid_reader").text("odczytaj karte.");
	//	alert("asdasd");
	//	$( "#name" ).data('name', name.msg);
	//	$("#rfid_dialog").dialog("close");
	});

});

$( "#rfid_save" ).click(function() {

$( "#progressbar_save" ).progressbar({
value: false
});

 $( "#rfid_save_dialog" ).dialog({
	position: { my: "center top", at: "center bottom", of: ground },
	resizable: false,
	dialogClass: "no-close"
});

	var name = $( "#name" ).val();
	var locker = $( "#locker" ).val();
	var machine = $( "#machine" ).val();
	$.ajax({
			url: 'save_rfid.php',
			type: 'post',
			data: {name: name, locker: locker, machine: machine},
			success: function(response){
				setTimeout(function () {
					$("#rfid_save_dialog").dialog("close");
			}, 3000);
			}
		});
});

$( "#calendar_href" ).click(function() {
	vacations = 1;
	$("#calendar").show();
	$('#calendar').fullCalendar("changeView", "agendaWeek" );
	$('#calendar').fullCalendar('removeEventSource', "getdata_vacation.php");
	$('#calendar').fullCalendar('refetchEvents');
	$("#info_div").hide();
	$("#users_div").hide();
	$("#bottom").show();
	$("#ground").css("height", "900px");
	$("#external-events").hide();
	$(".fc-button-agendaWeek").show();
});

$( "#info" ).click(function() {
	vacations = 1;
	$('#calendar').fullCalendar('removeEventSource', "getdata_vacation.php");
	$('#calendar').fullCalendar('refetchEvents');
	$("#users_div").hide();
	$("#ground").css("height", "auto");
	$("#info_div").show();
	$("#calendar").hide();
	$("#bottom").hide();
	$("#external-events").hide();
});

$( "#users" ).click(function() {
	vacations = 1;
	$('#calendar').fullCalendar('removeEventSource', "getdata_vacation.php");
	$('#calendar').fullCalendar('refetchEvents');
	$("#info_div").hide();
	$("#ground").css("height", "auto");
	$("#users_div").show();
	$("#calendar").hide();
	$("#bottom").hide();
	$("#external-events").hide();
});

$( "#logout" ).click(function() {
	$.ajax({
		type: "POST",
		url: "index.php",
		context: document.body,
		data: { logout: 1 }
})
	.done(function( s,x ) {
		//$(this).html(s); w ten sposob problem z new_user
		window.location.href = '?';
	});
});

$.ajax({
		type: "GET",
		async: false,
		url: "work_status.php"
})
	.done(function( msg ) {
		$( "#work" ).text(msg);
		work_status = msg;
});

$( "#work" ).click(function() {
	$.ajax({
		type: "POST",
		url: "work_status_change.php",
		data: { status: work_status }
})
	.done(function( msg ) {
		$('#calendar').fullCalendar( 'refetchEvents' ); // wyswietla pare eventow naraz(?)
		$( "#work" ).text(msg);
		work_status = msg;
	});
});

$( "#vacation" ).click(function() {
	$("#ground").css("height", "920px");
	$("#info_div").hide();
	$("#users_div").hide();
	$("#calendar").show();
	$("#bottom").show();
	//alert("vacation: " + vacations + "delegation: " + delegation);
	$('#calendar').fullCalendar("changeView", "month" );
	if(vacations == 1) {
		vacations_title = 1;
		//$('#vacation').css("border-bottom", "1px dotted");
		$('#calendar').fullCalendar('option', 'height', 640);
		$('#calendar').fullCalendar('addEventSource', "getdata_vacation.php" );
		$(".fc-button-agendaWeek").hide(); // ukrywanie przycisku miesiąc
		vacations = 0;
	} else {
		vacations_title = 0;
		//$('#vacation').css("border-bottom", "none");
		vacations_events = []; // czyscimy tablice jak zamkniemy urlopy
		$(".fc-button-agendaWeek").show();
		$('#calendar').fullCalendar('removeEventSource', "getdata_vacation.php");
		$('#calendar').fullCalendar('removeEventSource', "getdata.php");
		$('#calendar').fullCalendar("removeEvents");
		$('#calendar').fullCalendar('addEventSource', "getdata.php" );
		vacations = 1;
	}
	$( "#external-events" ).slideToggle();
});

$("#save_vacation").click(function() {
		$("#save_vacation").text("zapisano...").width(89);
		setTimeout(function(){
			$("#save_vacation").text("zapisz urlopy");
		}, 1000);
		for (var key in vacations_events) { // chujowa funkcja, tymczasowo, do zmiany bo generuje dla kazdego eventu zapytanie post..
			$.ajax({
			url: 'save_vacations.php',
			type: 'post',
			data: {event: vacations_events[key]},
			dataType: 'json',
			success: function(response){
				console.log('response');
			}
		});
			//alert(key + " -> " + vacations_events[key]);
		}
		vacations_events = [];
});

$("#save_users").click(function() {
	var str = $( "#users_save" ).serialize();
	$("#save_users").text("zapisano..").width(133);
	setTimeout(function(){
		$("#save_users").text("zapisz użytkowników");
	}, 1000);
	
	$.ajax({
			url: 'save_users.php',
			type: 'post',
			data: {data: str},
			dataType: 'json',
			success: function(response){
				console.log('response');
			}
		});
});

function addUser() {

	$( "#progressbar_save" ).progressbar({
		value: false
});

	$( "#rfid_save_dialog" ).dialog({
		position: { my: "center top", at: "center bottom", of: ground },
		resizable: false,
		dialogClass: "no-close"
});

	var str = $( "#new_user" ).serialize();
	
	$.ajax({
		type: "POST",
		url: "add_user.php",
		data: { data: str }
})
	.done(function( msg ) {
	setTimeout(function () {
		window.location.href = '?new_user';
					//$("#rfid_save_dialog").dialog("close");
	}, 3000);
		
	});

	$( this ).dialog( "close" );
	
}

$("#add_user").click(function() {

$( "#add_user_dialog" ).dialog({
	position: { my: "left top", at: "left bottom", of: users_div },
	draggable: true,
	resizable: false,
	dialogClass: "no-close",
	buttons: {
		"dodaj użytkownika": addUser,
		anuluj: function() {
			$( this ).dialog( "close" );
		}
	},
});

});

$(".delete_user").click(function() {

	$.ajax({
		type: "POST",
		url: "delete_user.php",
		data: { data: this.id }		
}).done(function( msg ) {
		window.location.href = '?new_user';
});

$("input[name='uid_"+this.name+"']").fadeOut(200,function(){$(this).remove();});
$("input[name='login_"+this.name+"']").fadeOut(200,function(){$(this).remove();});
$("input[name='password_"+this.name+"']").fadeOut(200,function(){$(this).remove();});
$("input[name='name_"+this.name+"']").fadeOut(200,function(){$(this).remove();});
$("input[name='admin_"+this.name+"']").fadeOut(200,function(){$(this).remove();});
$("button[name='"+this.name+"']").fadeOut(200,function(){$(this).remove();});

});

$('#external-events div.external-event').each(function() {

			// create an Event Object (http://arshaw.com/fullcalendar/docs/event_data/Event_Object/)
			// it doesn't need to have a start or end
			var eventObject = {
				title: $.trim($(this).text()), // use the element's text as the event title
				editable: true
			};
			
			// store the Event Object in the DOM element so we can get to it later
			$(this).data('eventObject', eventObject);
			
			// make the event draggable using jQuery UI
			$(this).draggable({
				zIndex: 999,
				revert: true,      // will cause the event to go back to its
				revertDuration: 0  //  original position after the drag
			});	
});
		
	var count = 0;
	
		$('#calendar').fullCalendar({
			header: {
				left: 'prev,next today',
				center: 'title',
				right: 'month,agendaWeek'
			},	
				
				droppable: true,
				eventColor: '#024873',
				defaultView: 'agendaWeek',
				editable: false,
				allDaySlot: false,
				allDayDefault: false,
				axisFormat: 'HH:mm',
				firstDay: 1,
				timeFormat: 'HH:mm{ - HH:mm}',
				monthNamesShort: ['Styczeń', 'Luty', 'Marzec', 'Kwiecień', 'Maj', 'Czerwiec', 'Lipiec', 'Sierpień', 'Wrzesień', 'Październik', 'Listopad', 'Grudzień'],
				buttonText: { today: 'dzisiaj', month: 'miesiąc', week: 'tydzień', day: 'dzień' },
				monthNames: ['Styczeń', 'Luty', 'Marzec', 'Kwiecień', 'Maj', 'Czerwiec', 'Lipiec', 'Sierpień', 'Wrzesień', 'Październik', 'Listopad', 'Grudzień'],
				dayNames: ['Niedziela', 'Poniedziałek', 'Wtorek', 'Środa', 'Czwartek', 'Piątek', 'Sobota'],
				dayNamesShort: ['Niedziela', 'Poniedziałek', 'Wtorek', 'Środa', 'Czwartek', 'Piątek', 'Sobota'],
				drop: function(date, allDay) { // this function is called when something is dropped
			
				// retrieve the dropped element's stored Event Object
				var originalEventObject = $(this).data('eventObject');
				
				// we need to copy it, so that multiple events don't have a reference to the same object
				var copiedEventObject = $.extend({}, originalEventObject);
				
				// assign it the date that was reported
				copiedEventObject.id = event_id;
				event_id++;
				copiedEventObject.start = date;
				copiedEventObject.allDay = allDay;
				copiedEventObject.color = "#24870f";
				
				// render the event on the calendar
				// the last `true` argument determines if the event "sticks" (http://arshaw.com/fullcalendar/docs/event_rendering/renderEvent/)
				$('#calendar').fullCalendar('renderEvent', copiedEventObject, true);
				var vacation_event_date = Date.parse(copiedEventObject.start);
				var vacation_event = new Date(vacation_event_date);
				var vac_day = vacation_event.getDate();
				var vac_month = vacation_event.getMonth() + 1;
				var vac_year = vacation_event.getFullYear();
				if (vac_day < 10)  vac_day = '0'+vac_day;
				if (vac_month < 10)  vac_month = '0'+vac_month;
				if (vac_year < 10)  vac_year = '0'+vac_year;
				//vacations_events.push("start=" + vac_year+"-"+vac_month+"-"+vac_day+"&title="+copiedEventObject.title + "&id="+copiedEventObject.id);
				//alert("start=" + vac_year+"-"+vac_month+"-"+vac_day + ", allDay=true");
				vacations_events[copiedEventObject.id] = "start=" + vac_year+"-"+vac_month+"-"+vac_day+"&title="+copiedEventObject.title;
			},
			
			viewRender: function( view, element ) {
				if(view.name == "month") {
					$('#calendar').fullCalendar('option', 'height', 680);
				} else {
					$('#calendar').fullCalendar('option', 'height', 680);
				}
			},
			
			eventDrop: function(event,dayDelta,minuteDelta,allDay,revertFunc) {
				var startTime = Date.parse(event.start);
				var DateStart = new Date(startTime);
				var endTime = Date.parse(event.end);
				var DateEnd = new Date(endTime);
				var vac_day_start = DateStart.getDate();
				var vac_month_start = DateStart.getMonth() + 1;
				var vac_year_start = DateStart.getFullYear();
				var vac_day_end = DateEnd.getDate() + 1;
				var vac_month_end = DateEnd.getMonth() + 1;
				var vac_year_end = DateEnd.getFullYear();
				if (vac_day_start < 10)  vac_day_start = '0'+vac_day_start;
				if (vac_month_start < 10)  vac_month_start = '0'+vac_month_start;
				if (vac_year_start < 10)  vac_year_start = '0'+vac_year_start;
				if (vac_day_end < 10)  vac_day_end = '0'+vac_day_end;
				if (vac_month_end < 10)  vac_month_end = '0'+vac_month_end;
				if (vac_year_end < 10)  vac_year_end = '0'+vac_year_end;
				if(isNaN(endTime)) {
					//vacations_events.push("start=" + vac_year_start+"-"+vac_month_start+"-"+vac_day_start + "&id="+event.id);
					vacations_events[event.id] = "start="+vac_year_start+"-"+vac_month_start+"-"+vac_day_start+"&title="+event.title;
					//for (var key in vacations_events) {
					//	alert(key + " -> " + vacations_events[key]);
					//}
				} else {
					vacations_events[event.id]="start="+vac_year_start+"-"+vac_month_start+"-"+vac_day_start+"&end="+vac_year_end+"-"+vac_month_end+"-"+vac_day_end+"&title="+event.title;
				}
				//alert("EVENT DROP" + vacations_events);
			},
			 
			eventRender: function(event, element) {
				element.bind('contextmenu', function() {
					if(event.editable) {
						vacations_events.splice(event.id, 1);
						$('#calendar').fullCalendar('removeEvents', event.id);
					}
					return false;
				});
			},
			
			eventResize: function(event,dayDelta,minuteDelta,revertFunc) {
				var startTime = Date.parse(event.start);
				var DateStart = new Date(startTime);
				var endTime = Date.parse(event.end);
				var DateEnd = new Date(endTime);
				var vac_day_start = DateStart.getDate();
				var vac_month_start = DateStart.getMonth() + 1;
				var vac_year_start = DateStart.getFullYear();
				var vac_day_end = DateEnd.getDate() + 1;
				var vac_month_end = DateEnd.getMonth() + 1;
				var vac_year_end = DateEnd.getFullYear();
				if (vac_day_start < 10)  vac_day_start = '0'+vac_day_start;
				if (vac_month_start < 10)  vac_month_start = '0'+vac_month_start;
				if (vac_year_start < 10)  vac_year_start = '0'+vac_year_start;
				if (vac_day_end < 10)  vac_day_end = '0'+vac_day_end;
				if (vac_month_end < 10)  vac_month_end = '0'+vac_month_end;
				if (vac_year_end < 10)  vac_year_end = '0'+vac_year_end;
				if(isNaN(endTime)) {
					vacations_events[event.id] = "start="+vac_year_start+"-"+vac_month_start+"-"+vac_day_start+"&title="+event.title;
				} else {
					vacations_events[event.id]="start="+vac_year_start+"-"+vac_month_start+"-"+vac_day_start+"&end="+vac_year_end+"-"+vac_month_end+"-"+vac_day_end+"&title="+event.title;
				}
				//alert("EVENT RESIZE" + vacations_events);
			},
			eventAfterRender: function(event, element, view) {
				if(vacations_title == 1) { //brak czasu dla eventow urlopowych
					if(event.title) {
						element.find(".fc-event-time").text("");
					}
				}
				var startTime = Date.parse(event.start);
				var DateStart = new Date(startTime);
				var endTime = Date.parse(event.end);
				var DateEnd = new Date(endTime);
				var start_hours = DateStart.getHours();
				var start_minutes = DateStart.getMinutes();
				var end_hours = DateEnd.getHours();
				var end_minutes = DateEnd.getMinutes();
				if (start_hours < 10)  start_hours = '0'+start_hours;
				if (start_minutes < 10)  start_minutes = '0'+start_minutes;
				if (end_hours < 10)  end_hours = '0'+end_hours;
				if (end_minutes < 10)  end_minutes = '0'+end_minutes;
				var diff_date = new Date(DateEnd - DateStart);
				var diff_hours = diff_date.getHours()-1;
				var diff_minutes = diff_date.getMinutes();
				if (diff_hours < 10)  diff_hours = '0'+diff_hours;
				if (diff_minutes < 10)  diff_minutes = '0'+diff_minutes;	
				if(view.name == 'agendaWeek') {
					if(diff_date.getTime() < 1500000) { // zwiekszanie wysokosci eventu jesli jest za krotki
						$(element).css('height','18px');
					}
					element.find(".fc-event-time").text(start_hours+":"+start_minutes + " - " + end_hours+":"+end_minutes);
					element.find(".fc-event-title").text("Czas: " + diff_hours + ":" + diff_minutes);
				}
			},
			eventSources: [
			{
				url: 'getdata.php'
			}],
			loading: function(bool) {
				if (bool) $('#loading').show();
				else $('#loading').hide();
			},
			
		});
});



